<?php
use think\Db;

/**1
 * 发送短信
 * @param unknown $phones	电话
 * @param unknown $content	短信内容
 * @param string $sign		签名
 * @return multitype:boolean string
 */
function send_msg($phones,$content,$sign='【奋斗大讲堂】'){

    $phones = (array)$phones;
    $target = 'http://sms.106jiekou.com/utf8/sms.aspx'; //短信URL
    //替换成自己的测试账号,参数顺序和wenservice对应
    $post_data = array(
        "account" => "fendouzhiyuan",
        "password" => "ssfeng0507",
        "mobile" => implode(",",$phones),
        "content" => rawurlencode($content)
    );
    $data = requestByPost($target,$post_data);
    $msg = '';
    $result = false;
    switch ($data){
        case 100:
            $msg = '发送成功';
            $result = true;
            break;
        case 101:
            $msg = '验证失败';
            $result = false;
            break;
        case 102:
            $msg = '手机号码格式不正确';
            $result = false;
            break;
        case 103:
            $msg = '会员级别不够';
            $result = false;
            break;
        case 104:
            $msg = '内容未审核';
            $result = false;
            break;
        case 105:
            $msg = '内容过多';
            $result = false;
            break;
        case 106:
            $msg = '账户余额不足';
            $result = false;
            break;
        case 107:
            $msg = 'Ip受限';
            $result = false;
            break;

        case 108:
            $msg = '手机号码发送太频繁，请换号或隔天再发';
            $result = false;
            break;
        case 109:
            $msg = '帐号被锁定';
            $result = false;
            break;
        case 110:
            $msg = '手机号发送频率持续过高，黑名单屏蔽数日';
            $result = false;
            break;
        case 120:
            $msg = '系统升级';
            $result = false;
            break;
    }
//	log_add('send_msg', $msg);
    return array("result"=>$result,"info"=>$msg);
}


/* @param $url
* @param bool $params 请求参数
* @param int $ispost 请求方式
* @param int $https https协议
* @return bool|mixed
*/
function curl($url, $params = false, $ispost = 0, $https = 0)
{
    $ch = curl_init();//初始化curl
    curl_setopt($ch, CURLOPT_URL, $url);//设置url属性
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    $output = curl_exec($ch);//获取数据
    curl_close($ch);//关闭curl
    return $output;
}

function curl_post($url, $post){
    $options = array(
        CURLOPT_RETURNTRANSFER =>true,
        CURLOPT_HEADER =>false,
        CURLOPT_POST =>true,
        CURLOPT_POSTFIELDS => $post,
    );
    $ch = curl_init($url);
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}


/**
 * curl的post请求
 *
 * @param string $url url网址
 * @param array $data post数组
 * @param int $timeout 超时时间
 * @return false 或 执行返回结果
 */

function requestByPost($url, $data, $timeout=3) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    $result = curl_exec($ch);

    if ($result !== false) {
        curl_close($ch);
        return $result;//$result;
    } else {
        $curl_error = curl_error($ch);
        $_data = is_array($data) ? implode('&', $data) : $data;
        curl_close($ch);
        error_log(__METHOD__ . ':' . $url . '?' . $_data . ':' . $curl_error);
        return false;
    }
}


function respon($success = 0, $res, $page = 0, $pageSize = 0)
{
    $result = array();

    $result['code'] = $success;
    if ($success==200) {
        $result['data']['list'] = $res;
        if ($page) $result['data']['page'] = $page;
        if ($pageSize) $result['data']['pageSize'] = $pageSize;
    } else {
        $result['error'] = $res;
    }
    //header("Content-Type: application/json; charset=utf-8");
    exit(json_encode($result));
}



// 应用公共文件
function p($str) {
    echo '<pre>';
    print_r($str);
}

function nodeTree($arr, $id = 0, $level = 0) {
    static $array = array();
    foreach ($arr as $v) {
        if ($v['parentid'] == $id) {
            $v['level'] = $level;
            $array[] = $v;
            nodeTree($arr, $v['id'], $level + 1);
        }
    }
    return $array;
}

/**
 * 数组转树
 * @param type $list
 * @param type $root
 * @param type $pk
 * @param type $pid
 * @param type $child
 * @return type
 */
function list_to_tree($list, $root = 0, $pk = 'id', $pid = 'parentid', $child = '_child') {
    // 创建Tree
    $tree = array();
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = 0;
            if (isset($data[$pid])) {
                $parentId = $data[$pid];
            }
            if ((string) $root == $parentId) {
                $tree[] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * 下拉选择框
 */
function select($array = array(), $id = 0, $str = '', $default_option = '') {
    $string = '<select ' . $str . '>';
    $default_selected = (empty($id) && $default_option) ? 'selected' : '';
    if ($default_option)
        $string .= "<option value='' $default_selected>$default_option</option>";
    if (!is_array($array) || count($array) == 0)
        return false;
    $ids = array();
    if (isset($id))
        $ids = explode(',', $id);
    foreach ($array as $key => $value) {
        $selected = in_array($key, $ids) ? 'selected' : '';
        $string .= '<option value="' . $key . '" ' . $selected . '>' . $value . '</option>';
    }
    $string .= '</select>';
    return $string;
}

/**
 * 复选框
 * 
 * @param $array 选项 二维数组
 * @param $id 默认选中值，多个用 '逗号'分割
 * @param $str 属性
 * @param $defaultvalue 是否增加默认值 默认值为 -99
 * @param $width 宽度
 */
function checkbox($array = array(), $id = '', $str = '', $defaultvalue = '', $width = 0, $field = '') {
    $string = '';
    $id = trim($id);
    if ($id != '')
        $id = strpos($id, ',') ? explode(',', $id) : array($id);
    if ($defaultvalue)
        $string .= '<input type="hidden" ' . $str . ' value="-99">';
    $i = 1;
    foreach ($array as $key => $value) {
        $key = trim($key);
        $checked = ($id && in_array($key, $id)) ? 'checked' : '';
        if ($width)
            $string .= '<label class="ib" style="width:' . $width . 'px">';
        $string .= '<input type="checkbox" ' . $str . ' id="' . $field . '_' . $i . '" ' . $checked . ' value="' . $key . '"> ' . $value;
        if ($width)
            $string .= '</label>';
        $i++;
    }
    return $string;
}

/**
 * 单选框
 * 
 * @param $array 选项 二维数组
 * @param $id 默认选中值
 * @param $str 属性
 */
function radio($array = array(), $id = 0, $str = '', $width = 0, $field = '') {
    $string = '';
    foreach ($array as $key => $value) {
        $checked = trim($id) == trim($key) ? 'checked' : '';
        if ($width)
            $string .= '<label class="ib" style="width:' . $width . 'px">';
        $string .= '<input type="radio" ' . $str . ' id="' . $field . '_' . $key . '" ' . $checked . ' value="' . $key . '"> ' . $value;
        if ($width)
            $string .= '</label>';
    }
    return $string;
}

/**
 * 字符串加密、解密函数
 *
 *
 * @param	string	$txt		字符串
 * @param	string	$operation	ENCODE为加密，DECODE为解密，可选参数，默认为ENCODE，
 * @param	string	$key		密钥：数字、字母、下划线
 * @param	string	$expiry		过期时间
 * @return	string
 */
function encry_code($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5($key != '' ? $key : config('encry_key'));
    $keya = md5(substr($key, 0, 16));
    $keyb = md5(substr($key, 16, 16));
    $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';

    $cryptkey = $keya . md5($keya . $keyc);
    $key_length = strlen($cryptkey);

    $string = $operation == 'DECODE' ? base64_decode(strtr(substr($string, $ckey_length), '-_', '+/')) : sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
    $string_length = strlen($string);

    $result = '';
    $box = range(0, 255);

    $rndkey = array();
    for ($i = 0; $i <= 255; $i++) {
        $rndkey[$i] = ord($cryptkey[$i % $key_length]);
    }

    for ($j = $i = 0; $i < 256; $i++) {
        $j = ($j + $box[$i] + $rndkey[$i]) % 256;
        $tmp = $box[$i];
        $box[$i] = $box[$j];
        $box[$j] = $tmp;
    }

    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        $tmp = $box[$a];
        $box[$a] = $box[$j];
        $box[$j] = $tmp;
        $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
    }

    if ($operation == 'DECODE') {
        if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
            return substr($result, 26);
        } else {
            return '';
        }
    } else {
        return $keyc . rtrim(strtr(base64_encode($result), '+/', '-_'), '=');
    }
}

/**
 * 截取字符串
 */
function WSTMSubstr($str, $start = 0, $length, $charset = "utf-8", $suffix = false){
    $newStr = '';
    if (function_exists ( "mb_substr" )) {
        if ($suffix){
            $newStr = mb_substr ( $str, $start, $length, $charset )."...";
        }else{
            $newStr = mb_substr ( $str, $start, $length, $charset );
        }
    } elseif (function_exists ( 'iconv_substr' )) {
        if ($suffix){
            $newStr = iconv_substr ( $str, $start, $length, $charset )."...";
        }else{
            $newStr = iconv_substr ( $str, $start, $length, $charset );
        }
    }
    if($newStr==''){
        $re ['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re ['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re ['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re ['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all ( $re [$charset], $str, $match );
        $slice = join ( "", array_slice ( $match [0], $start, $length ) );
        if ($suffix)
            $newStr = $slice;
    }
    return $newStr;
}
function WSTScore($score,$users,$type = 5,$len = 0,$total = 1){
    if((int)$score==0)return $type;
    switch($type){
        case 5:return round($score/$total/$users,0);
        case 10:return round($score/$total*2/$users,$len);
        case 100:return round($score/$total*2/$users,$len);
    }
}

/**
 * 生成随机数账号
 */
function WSTRandomLoginName($loginName){
    $chars = array("a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z");
    //简单的派字母
    foreach ($chars as $key =>$c){
        $crs = WSTCheckLoginKey($loginName."_".$c);
        if($crs['status']==1)return $loginName."_".$c;
    }
    //随机派三位数值
    for($i=0;$i<1000;$i++){
        $crs = $this->WSTCheckLoginKey($loginName."_".$i);
        if($crs['status']==1)return $loginName."_".$i;
    }
    return '';
}

/**
 * 删除一维数组里的多个key
 */
function WSTUnset(&$data,$keys){
    if($keys!='' && is_array($data)){
        $key = explode(',',$keys);
        foreach ($key as $v)unset($data[$v]);
    }
}
/**
 * 只允许一维数组里的某些key通过
 */
function WSTAllow(&$data,$keys){
    if($keys!='' && is_array($data)){
        $key = explode(',',$keys);
        foreach ($data as $vkeys =>$v)if(!in_array($vkeys,$key))unset($data[$vkeys]);
    }
}

/**
 * 生成验证码
 */
function WSTVerify(){
    $Verify = new \verify\Verify();
    $Verify->length   = 4;
    $Verify->entry();
}
/**
 * 核对验证码
 */
function WSTVerifyCheck($code){
    $verify = new \verify\Verify();
    return $verify->check($code);
}



/**
 * 生成数据返回值
 */
function WSTReturn($msg,$status = -1,$data = []){
    $rs = ['status'=>$status,'msg'=>$msg];
    if(!empty($data))$rs['data'] = $data;
    return json_encode($rs);
}

/**
 * 检测字符串不否包含
 * @param $srcword 被检测的字符串
 * @param $filterWords 禁用使用的字符串列表
 * @return boolean true-检测到,false-未检测到
 */
function WSTCheckFilterWords($srcword,$filterWords){
    $flag = true;
    if($filterWords!=""){
        $filterWords = str_replace("，",",",$filterWords);
        $words = explode(",",$filterWords);
        for($i=0;$i<count($words);$i++){
            if(strpos($srcword,$words[$i]) !== false){
                $flag = false;
                break;
            }
        }
    }
    return $flag;
}

/**
 * 中国网建短信服务商
 * @param string $phoneNumer  手机号码
 * @param string $content     短信内容
 */
function WSTSendSMS($phoneNumer,$content){
    $url = 'http://utf8.sms.webchinese.cn/?Uid='.WSTConf("CONF.smsKey").'&Key='.WSTConf("CONF.smsPass").'&smsMob='.$phoneNumer.'&smsText='.$content;
    $ch=curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//设置否输出到页面
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30 ); //设置连接等待时间
    curl_setopt($ch, CURLOPT_ENCODING, "gzip" );
    $data=curl_exec($ch);
    curl_close($ch);
    return $data;
}


/**
 * 获取指定的全局配置
 */
function WSTConf($key,$v = ''){
    if(is_null($v)){
        if(array_key_exists('WSTMARTCONF',$GLOBALS) && array_key_exists($key,$GLOBALS['WSTMARTCONF'])){
            unset($GLOBALS['WSTMARTCONF'][$key]);
        }
    }else if($v === ''){
        if(array_key_exists('WSTMARTCONF',$GLOBALS)){
            $conf = $GLOBALS['WSTMARTCONF'];
            $ks = explode(".",$key);
            for($i=0,$k=count($ks);$i<$k;$i++){
                if(array_key_exists($ks[$i],$conf)){
                    $conf = $conf[$ks[$i]];
                }else{
                    return null;
                }
            }
            return $conf;
        }
    }else{
        return $GLOBALS['WSTMARTCONF'][$key] = $v;
    }
    return null;
}

//php获取中文字符拼音首字母
function WSTGetFirstCharter($str){
    if(empty($str)){
        return '';
    }
    $fchar=ord($str{0});
    if($fchar>=ord('A')&&$fchar<=ord('z')) return strtoupper($str{0});
    $s1=iconv('UTF-8','gb2312',$str);
    $s2=iconv('gb2312','UTF-8',$s1);
    $s=$s2==$str?$s1:$str;
    if(empty($s{1})){
        return '';
    }
    $asc=ord($s{0})*256+ord($s{1})-65536;
    if($asc>=-20319 && $asc<=-20284) return 'A';
    if($asc>=-20283 && $asc<=-19776) return 'B';
    if($asc>=-19775 && $asc<=-19219) return 'C';
    if($asc>=-19218 && $asc<=-18711) return 'D';
    if($asc>=-18710 && $asc<=-18527) return 'E';
    if($asc>=-18526 && $asc<=-18240) return 'F';
    if($asc>=-18239 && $asc<=-17923) return 'G';
    if($asc>=-17922 && $asc<=-17418) return 'H';
    if($asc>=-17417 && $asc<=-16475) return 'J';
    if($asc>=-16474 && $asc<=-16213) return 'K';
    if($asc>=-16212 && $asc<=-15641) return 'L';
    if($asc>=-15640 && $asc<=-15166) return 'M';
    if($asc>=-15165 && $asc<=-14923) return 'N';
    if($asc>=-14922 && $asc<=-14915) return 'O';
    if($asc>=-14914 && $asc<=-14631) return 'P';
    if($asc>=-14630 && $asc<=-14150) return 'Q';
    if($asc>=-14149 && $asc<=-14091) return 'R';
    if($asc>=-14090 && $asc<=-13319) return 'S';
    if($asc>=-13318 && $asc<=-12839) return 'T';
    if($asc>=-12838 && $asc<=-12557) return 'W';
    if($asc>=-12556 && $asc<=-11848) return 'X';
    if($asc>=-11847 && $asc<=-11056) return 'Y';
    if($asc>=-11055 && $asc<=-10247) return 'Z';
    return null;
}

/**
 * 设置当前页面对象
 * @param int 0-用户  1-商家
 */
function WSTLoginTarget($target = 0){
    $WST_USER = session('WST_USER');
    $WST_USER['loginTarget'] = $target;
    session('WST_USER',$WST_USER);
}
/**
 * 邮件发送函数
 * @param string to      要发送的邮箱地址
 * @param string subject 邮件标题
 * @param string content 邮件内容
 * @return array
 */
function WSTSendMail($to, $subject, $content) {
    $mail = new \phpmailer\phpmailer();
    // 装配邮件服务器
    $mail->IsSMTP();
    $mail->SMTPDebug = 0;
    $mail->Host = WSTConf("CONF.mailSmtp");
    $mail->SMTPAuth = WSTConf("CONF.mailAuth");
    $mail->Username = WSTConf("CONF.mailUserName");
    $mail->Password = WSTConf("CONF.mailPassword");
    $mail->CharSet = 'utf-8';
    // 装配邮件头信息
    $mail->From = WSTConf("CONF.mailAddress");
    $mail->AddAddress($to);
    $mail->FromName = WSTConf("CONF.mailSendTitle");
    $mail->IsHTML(true);
    // 装配邮件正文信息
    $mail->Subject = $subject;
    $mail->Body = $content;
    // 发送邮件
    $rs =array();
    if (!$mail->Send()) {
        $rs['status'] = 0;
        $rs['msg'] = $mail->ErrorInfo;
        return $rs;
    } else {
        $rs['status'] = 1;
        return $rs;
    }
}

/**
 * 获取系统配置数据
 */
function WSTConfig(){
    $rs = cache('WST_CONF');
    if(!$rs){
        $rv = Db::name('sys_configs')->field('fieldCode,fieldValue')->select();
        $rs = [];
        foreach ($rv as $v){
            $rs[$v['fieldCode']] = $v['fieldValue'];
        }
        //获取风格
        $styles = Db::name('styles')->where(['styleSys'=>0,'isUse'=>1])->field('stylePath,id')->find();
        if(!empty($styles)){
            $rs['wstPcStyle'] = $styles['stylePath'];
            $rs['wstPcStyleId'] = $styles['id'];
        }else{
            $rs['wstPcStyle'] = 'default';
            $rs['wstPcStyleId'] = 0;
        }
        //获取上传文件目录配置
        $data = Db::name('datas')->where('catId',3)->column('dataVal');
        foreach ($data as $key => $v){
            $data[$key] = str_replace('_','',$v);
        }
        $rs['wstUploads'] = $data;
        if(WSTConf('CONF.mallLicense')=='')$rs['mallSlogan'] = $rs['mallSlogan']."  ".base64_decode('UG93ZXJlZCBCeSBXU1RNYXJ0');
        cache('WST_CONF',$rs,31536000);
    }
    return $rs;
}

/**
 * 判断手机号格式是否正确
 */
function WSTIsPhone($phoneNo){
    $reg = "/^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$/";
    $rs = \think\Validate::regex($phoneNo,$reg);
    return $rs;
}

/**
 * 检测登录账号是否可用
 * @param $key 要检测的内容
 */
function WSTCheckLoginKey($val,$userId = 0){
    if($val=='')return WSTReturn("登录账号不能为空");
    if(!WSTCheckFilterWords($val,WSTConf("CONF.registerLimitWords"))){
        return WSTReturn("登录账号包含非法字符");
    }
    $dbo = Db::name('users')->where(["loginName|userEmail|userPhone"=>['=',$val],'dataFlag'=>1]);
    if($userId>0){
        $dbo->where("userId", "<>", $userId);
    }
    $rs = $dbo->count();
    if($rs==0){
        return WSTReturn("该登录账号可用",1);
    }
    return WSTReturn("对不起，登录账号已存在");
}

/**
 * 字符串替换
 * @param string $str     要替换的字符串
 * @param string $repStr  即将被替换的字符串
 * @param int $start      要替换的起始位置,从0开始
 * @param string $splilt  遇到这个指定的字符串就停止替换
 */
function WSTStrReplace($str,$repStr,$start,$splilt = ''){
    $newStr = substr($str,0,$start);
    $breakNum = -1;
    for ($i=$start;$i<strlen($str);$i++){
        $char = substr($str,$i,1);
        if($char==$splilt){
            $breakNum = $i;
            break;
        }
        $newStr.=$repStr;
    }
    if($splilt!='' && $breakNum>-1){
        for ($i=$breakNum;$i<strlen($str);$i++){
            $char = substr($str,$i,1);
            $newStr.=$char;
        }
    }
    return $newStr;
}

/**
 * 上传图片
 * 需要生成缩略图： isThumb=1
 * 需要加水印：isWatermark=1
 * pc版缩略图： width height
 * 手机版原图：mWidth mHeight
 * 缩略图：mTWidth mTHeight
 * 判断图片来源：$type  上传类型 1:认证,2:头像,3:其他
 */
function Upload($file,$type){
   /* $fileKey = key($_FILES);
    $dir = Input('post.dir');
    if($dir=='')return json_encode(['msg'=>'没有指定文件目录！','status'=>-1]);
    $dirs = WSTConf("CONF.wstUploads");
    if(!in_array($dir, $dirs)){
        return json_encode(['msg'=>'非法文件目录！','status'=>-1]);
    }*/
    $dir = 'Img';
    // 上传文件
    //$file = request()->file($fileKey);
    if($file===null){
        return array('msg'=>'上传文件不存在或超过服务器限制','status'=>-1);
    }
    $validate = new \think\Validate([
        ['fileMime','fileMime:image/png,image/gif,image/jpeg,image/x-ms-bmp','只允许上传jpg,gif,png,bmp类型的文件'],
        ['fileExt','fileExt:jpg,jpeg,gif,png,bmp','只允许上传后缀为jpg,gif,png,bmp的文件'],
        ['fileSize','fileSize:2097152','文件大小超出限制'],//最大2M
    ]);
    $data = ['fileMime'  => $file,
        'fileSize' => $file,
        'fileExt'=> $file
    ];
    //return $data;die;
    if (!$validate->check($data)) {
        return array('msg'=>$validate->getError(),'status'=>-1);
    }
    $info = $file->rule('uniqid')->move(ROOT_PATH.'/upload/'.$dir."/".date('Y-m'));
    if($info){
        $filePath = $info->getPathname();
        $filePath = str_replace(ROOT_PATH,'',$filePath);
        $filePath = str_replace('\\','/',$filePath);
        $name = $info->getFilename();
        $filePath = str_replace($name,'',$filePath);
        //原图路径
        $imageSrc = trim($filePath.$name,'/');
        if($type == 1){
            return $imageSrc;die;
        }
        //图片记录
        WSTRecordImages($imageSrc, (int)$userid);
        //打开原图
        $image = \image\Image::open($imageSrc);
        //缩略图路径 手机版原图路径 手机版缩略图路径
        $thumbSrc = $mSrc = $mThumb = null;
        //手机版原图宽高
        $mWidth = min($image->width(),(int)input('mWidth',700));
        $mHeight = min($image->height(),(int)input('mHeight',700));
        //手机版缩略图宽高
        $mTWidth = min($image->width(),(int)input('mTWidth',250));
        $mTHeight = min($image->height(),(int)input('mTHeight',250));

        /****************************** 生成缩略图 *********************************/
        $isThumb = (int)input('isThumb');
        if($isThumb==1){
            //缩略图路径
            $thumbSrc = str_replace('.', '_thumb.', $imageSrc);
            $image->thumb((int)input('width',min(300,$image->width())), (int)input('height',min(300,$image->height())),2)->save($thumbSrc,$image->type(),90);
            //是否需要生成移动版的缩略图
            $suffix = WSTConf("CONF.wstMobileImgSuffix");
            if(!empty($suffix)){
                $image = \image\Image::open($imageSrc);
                $mSrc = str_replace('.',"$suffix.",$imageSrc);
                $mThumb = str_replace('.', '_thumb.',$mSrc);
                $image->thumb($mWidth, $mHeight)->save($mSrc,$image->type(),90);
                $image->thumb($mTWidth, $mTHeight, 2)->save($mThumb,$image->type(),90);
            }


        }
        /***************************** 添加水印 ***********************************/
        $isWatermark=(int)input('isWatermark');
        if($isWatermark==1 && (int)WSTConf('CONF.watermarkPosition')!==0){
            //取出水印配置
            $wmWord = WSTConf('CONF.watermarkWord');//文字
            $wmFile = trim(WSTConf('CONF.watermarkFile'),'/');//水印文件
            $wmPosition = (int)WSTConf('CONF.watermarkPosition');//水印位置
            $wmSize = ((int)WSTConf('CONF.watermarkSize')!=0)?WSTConf('CONF.watermarkSize'):'20';//大小
            $wmColor = (WSTConf('CONF.watermarkColor')!='')?WSTConf('CONF.watermarkColor'):'#000000';//颜色必须是16进制的
            $wmOpacity = ((int)WSTConf('CONF.watermarkOpacity')!=0)?WSTConf('CONF.watermarkOpacity'):'100';//水印透明度
            //是否有自定义字体文件
            $customTtf = $_SERVER['DOCUMENT_ROOT'].WSTConf('CONF.watermarkTtf');
            $ttf = is_file($customTtf)?$customTtf:EXTEND_PATH.'/verify/verify/ttfs/3.ttf';
            $image = \image\Image::open($imageSrc);
            if(!empty($wmWord)){//当设置了文字水印 就一定会执行文字水印,不管是否设置了文件水印

                //执行文字水印
                $image->text($wmWord, $ttf, $wmSize, $wmColor, $wmPosition)->save($imageSrc);
                if($thumbSrc!==null){
                    $image->thumb((int)input('width',min(300,$image->width())), (int)input('height',min(300,$image->height())),2)->save($thumbSrc,$image->type(),90);
                }
                //如果有生成手机版原图
                if(!empty($mSrc)){
                    $image = \image\Image::open($imageSrc);
                    $image->thumb($mWidth, $mHeight)->save($mSrc,$image->type(),90);
                    $image->thumb($mTWidth, $mTHeight, 2)->save($mThumb,$image->type(),90);
                }
            }elseif(!empty($wmFile)){//设置了文件水印,并且没有设置文字水印
                //执行图片水印
                $image->water($wmFile, $wmPosition, $wmOpacity)->save($imageSrc);
                if($thumbSrc!==null){
                    $image->thumb((int)input('width',min(300,$image->width())), (int)input('height',min(300,$image->height())),2)->save($thumbSrc,$image->type(),90);
                }
                //如果有生成手机版原图
                if($mSrc!==null){
                    $image = \image\Image::open($imageSrc);
                    $image->thumb($mWidth, $mHeight)->save($mSrc,$image->type(),90);
                    $image->thumb($mTWidth, $mTHeight,2)->save($mThumb,$image->type(),90);
                }
            }
        }
        //判断是否有生成缩略图
        $thumbSrc = ($thumbSrc==null)?$info->getFilename():str_replace('.','_thumb.', $info->getFilename());
        $filePath = ltrim($filePath,'/');
        // 用户头像上传宽高限制
        $isCut = (int)input('isCut');
        if($isCut){
            $imgSrc = $filePath.$info->getFilename();
            $image = \image\Image::open($imgSrc);
            $size = $image->size();//原图宽高
            $w = $size[0];
            $h = $size[1];
            $rate = $w/$h;
            if($w>$h && $w>500){
                $newH = 500/$rate;
                $image->thumb(500, $newH)->save($imgSrc,$image->type(),90);
            }elseif($h>$w && $h>500){
                $newW = 500*$rate;
                $image->thumb($newW, 500)->save($imgSrc,$image->type(),90);
            }
        }
        return json_encode(['status'=>1,'savePath'=>$filePath,'name'=>$info->getFilename(),'thumb'=>$thumbSrc]);
    }else{
        //上传失败获取错误信息
        return $file->getError();
    }
}

/**
 * 图片管理
 * @param $imgPath    图片路径
 * @param $fromType   0：用户/商家 1：平台管理员
 *
 */
function WSTRecordImages($imgPath, $userid){
    $data = [];
    var_dump($imgPath);die;
    $data['imgPath'] = $imgPath;
    if(file_exists($imgPath)){
        $data['imgSize'] = filesize($imgPath); //返回字节数 imgsize/1024 k  	imgsize/1024/1024 m
    }
    //获取表名
    $table = explode('/',$imgPath);
    $data['fromTable'] = $table[1];
    $data['fromType'] = (int)$fromType;
    //根据类型判断所有者
    $data['ownId'] = ((int)$fromType==0)?(int)session('WST_USER.userId'):(int)session('WST_STAFF.staffId');
    $data['isUse'] = 0; //默认不使用
    $data['createTime'] = date('Y-m-d H:i:s');

    //保存记录
    Db::name('images')->insert($data);

}



/**
 * 上传文件
 */
function WSTUploadFile(){
    $fileKey = key($_FILES);
    $dir = Input('post.dir');
    if($dir=='')return json_encode(['msg'=>'没有指定文件目录！','status'=>-1]);
    $dirs = WSTConf("CONF.wstUploads");
    if(!in_array($dir, $dirs)){
        return json_encode(['msg'=>'非法文件目录！','status'=>-1]);
    }
    //上传文件
    $file = request()->file($fileKey);
    if($file===null){
        return json_encode(['msg'=>'上传文件不存在或超过服务器限制','status'=>-1]);
    }
    $validate = new \think\Validate([
        ['fileExt','fileExt:xls,xlsx,xlsm','只允许上传后缀为xls,xlsx,xlsm的文件']
    ]);
    $data = ['fileExt'=> $file];
    if (!$validate->check($data)) {
        return json_encode(['msg'=>$validate->getError(),'status'=>-1]);
    }
    $info = $file->rule('uniqid')->move(ROOT_PATH.'/upload/'.$dir."/".date('Y-m'));
    //保存路径
    $filePath = $info->getPathname();
    $filePath = str_replace(ROOT_PATH,'',$filePath);
    $filePath = str_replace('\\','/',$filePath);
    $name = $info->getFilename();
    $filePath = str_replace($name,'',$filePath);
    if($info){
        return json_encode(['status'=>1,'name'=>$info->getFilename(),'route'=>$filePath]);
    }else{
        //上传失败获取错误信息
        return $file->getError();
    }
}

/**
 * 分页
 * @param unknown $page     页数
 * @param unknown $length   显示条数
 */
function wechat_page($page='1',$length='5'){
    $page = $page>0 ? $page : 1;
    $offset = ($page-1)*$length;
    $arr['offset'] = $offset;
    $arr['length'] = $length;
    return $arr;
}

/**
 * 处理token类型，转换为汉字
 * @param unknown $arr 传入的二维数组
 *  0影人认证.1注册.2评论3.转发4.点赞5.发布短评6.发布长评7.上传电影票根8.登录
 */
function token_arr($arr){
    $data=array();
    foreach ($arr as $k=>$v){
        switch($v['to_type']) {
            case 0: // 表达式
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='登录';
                continue;
            case 1: // 表达式
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='注册';
                continue;
            case 2:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='评论';
                continue;
            case 3:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='转发';
            case 4:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='点赞';
                continue;
            case 5:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='发布短评';
                continue;
            case 6:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='发布长评';
                continue;
            case 7:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='上传电影票根';
                continue;
            default:
                $data[$k]['token']=$v['token'];
                $data[$k]['created_at']=$v['created_at'];
                $data[$k]['to_type']='登录';
                continue;
        }
    }
    return $data;
}

/*
 *处理收藏查询的结果，重新组合数据
 *
 * **/
    function collect_arr($result){
        $data=array();
        foreach ($result as $key=>$value){
            if($value['type']==1){
                $data['movie_id'][]=$value['movie_id'];
            }elseif ($value['type']==2){
                $data['item_id'][]=$value['item_id'];
            }
        }
        foreach ($data as $k=>$v){
            $data[$k]=implode(',',$v);
        }
        return $data;
    }



/*
*处理足迹查询的结果，重新组合数据
*
* **/
function foot_arr($result){
    $data=array();
    foreach ($result as $key=>$value){
        if($value['fp_type']==1){
            $data['movie_id'][]=$value['fp_conid'];
        }elseif ($value['type']==2){
            $data['item_id'][]=$value['fp_conid'];
        }
    }
    foreach ($data as $k=>$v){
        $data[$k]=implode(',',$v);
    }
    return $data;
}

/**
 * @param $table
 * @param $userid
 * @return string
 */
function get_hash_table($table, $userid)
{
    $str = crc32($userid);


    if ($str < 0) {
        $hash = "0" . substr(abs($str), 0, 1);
    } else {
        $hash = substr($str, 0, 2);
    }


    return $table . "_" . $hash;
}


/**
 * @param $table_name
 * @param $user_id
 * @param $total
 * @return string
 */
function hash_table($table_name, $user_id, $total)
{
    return $table_name . '_' . (($user_id % $total) + 1);
}

/*
 * 查询电影评论公共方法
 *$user_id 用户id
 * $movie_id 电影id
 * $type 评论类型 0是全部1短评2长评
 *
 * **/
function movies_review($user_id=null,$movie_id,$type,$offset=0,$length=5){
    if($user_id){
        $where='user_id = '.$user_id.' and status = 1';
        $result =Db::name('film_review')->where($where)->field('movie_id,movie_name,title,rate,type,s_review,l_review,like_count,comment_count,created_at')->limit($offset,$length)->select();

    }

    if($movie_id && $type==0){
        $where='movie_id = '.$movie_id .' and status = 1';
        $result = Db::name('film_review')->where($where)->field('id,user_id,movie_id,movie_name,title,rate,type,s_review,l_review,like_count,comment_count,created_at')->limit($offset,$length)->select();

    }elseif($movie_id && $type!=0){
        $where='movie_id = '.$movie_id .' and status = 1 and type = '.$type;
        $result = Db::name('film_review')->where($where)->field('id,user_id,movie_id,movie_name,title,rate,type,s_review,l_review,like_count,comment_count,created_at')->limit($offset,$length)->select();
    }
    foreach ($result as &$v){
        $phone=Db::name('user')->where('id= '.$v['user_id'])->field('phone')->find();
        $dt=Db::name('user_extend')->where('phone= '.$phone['phone'])->field('nickname,openid,avatar_url')->find();

        $v['author'] = $dt;
    }

    return $result;
}

/*
 * 动作奖励token公共方法
 *$user_id 用户id
 * $type 动作类型 0影人认证.1注册.2评论3.转发4.点赞5.发布短评6.发布长评7.上传电影票根.8登录
 *121212
 * **/
    function reward_token($user_id,$type){
        switch ($type){
            case 0:
                $token=8888;
                break;
            case 1:
                $token=888;
                break;
            case 2:
                $token=88;
                break;
            case 3:
                $token=366;
                break;
            case 4:
                $token=66;
                break;
            case 5:
                $token=388;
                break;
            case 6:
                $token=888;
                break;
            case 7:
                $token=666;
                break;
            default:
                $token=88;
                break;
        }
        $data['user_id']=$user_id;
        $data['type']=$type;
        $data['status']=1;
        $data['created_at']=date('Y-m-d H:i:s', time());

        $beforetoken = Db::name('token')->where('user_id',$user_id)->select();
        if($beforetoken[0]['after_token']){
            $data['before_token'] = $beforetoken[0]['after_token'];
            $data['change_token']=$token;
            $data['after_token']=$beforetoken[0]['after_token']+$token;
            $result=Db::name('token')->update($data);
        }else{
            $data['before_token'] =0;
            $data['change_token']=$token;
            $data['after_token']=$token;
            $result=Db::name('token')->insert($data);
        }
        return $result;

    }
